package cn.bonoon.handler.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import cn.bonoon.handler.RedirectToUserHome;
import cn.bonoon.kernel.AccessAuthorityResolver;
import cn.bonoon.kernel.menus.ModuleDefinition;
import cn.bonoon.kernel.security.LogonUser;

/**
 * <pre>
 * 默认的情况；
 * 
 * 以后需要加入根据当前用户自己定义的首页进入，即自定义的系统进入点
 * </pre>
 * @author jackson
 *
 */
public class DefaultLoginSuccessRedirect implements RedirectToUserHome, ApplicationContextAware{

	private ApplicationContext applicationContext;
	
	public final void setApplicationContext(ApplicationContext context) throws BeansException {
		applicationContext = context;
	}

	private String targetUrl;

	@Override
	public String redirectUrl(HttpServletRequest request, HttpServletResponse response, LogonUser logonUser) {

        String targetUrl = this.targetUrl;

        if (!StringUtils.hasText(targetUrl)) {
        	AccessAuthorityResolver resolver = AccessAuthorityResolver.valueOf(applicationContext, logonUser);
        	if(logonUser.allowAccess()){

				for(ModuleDefinition module : resolver.resolveModules()){
					targetUrl = module.getEndpoint();
					
					//只取第一个
					break;
				}
				
				if (!StringUtils.hasText(targetUrl)) {
					targetUrl = resolver.plaformUrl();
				}
			}else{
				targetUrl = resolver.homeUrl();
			}
        }
        
		return targetUrl;
	}
	
	public void setTargetUrl(String targetUrl) {
		this.targetUrl = targetUrl;
	}
}
